<template>
  <a-drawer
    v-model:visible="visible"
    title="配置数据详情"
    placement="right"
    :width="800"
    :closable="true"
    :mask-closable="true"
    @close="handleClose"
  >
    <template #extra>
      <a-space>
        <a-button v-if="config" type="primary" size="small" @click="exportConfig">
          导出配置
        </a-button>
        <a-button type="default" size="small" @click="handleClose">
          关闭
        </a-button>
      </a-space>
    </template>

    <div v-if="config" class="config-detail">
      <!-- 基本信息 -->
      <a-card title="基本信息" class="mb-4">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="配置ID">
            {{ config.configId }}
          </a-descriptions-item>
          <a-descriptions-item label="配置类型">
            <a-tag :color="getConfigTypeColor(config.configType)">
              {{ getConfigTypeName(config.configType) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="渠道代码">
            {{ config.channelCode }}
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- 配置数据 -->
      <a-card title="配置数据" class="mb-4">
        <div class="config-data-container">
          <pre class="config-json">{{ formatConfigData(config.configData) }}</pre>
        </div>
      </a-card>

      <!-- 配置数据表格视图 -->
      <a-card title="配置数据解析" v-if="parsedConfigData">
        <a-tabs>
          <a-tab-pane key="basic" tab="基础配置">
            <ConfigDataTable :data="parsedConfigData.basic" />
          </a-tab-pane>
          <a-tab-pane key="routing" tab="路由配置" v-if="parsedConfigData.routing">
            <ConfigDataTable :data="parsedConfigData.routing" />
          </a-tab-pane>
          <a-tab-pane key="direct" tab="直连配置" v-if="parsedConfigData.direct">
            <ConfigDataTable :data="parsedConfigData.direct" />
          </a-tab-pane>
          <a-tab-pane key="security" tab="安全配置" v-if="parsedConfigData.security">
            <ConfigDataTable :data="parsedConfigData.security" />
          </a-tab-pane>
          <a-tab-pane key="crypto" tab="加密配置" v-if="parsedConfigData.crypto">
            <ConfigDataTable :data="parsedConfigData.crypto" />
          </a-tab-pane>
          <a-tab-pane key="limits" tab="限制配置" v-if="parsedConfigData.limits">
            <ConfigDataTable :data="parsedConfigData.limits" />
          </a-tab-pane>
          <a-tab-pane key="products" tab="产品配置" v-if="parsedConfigData.products">
            <ConfigDataTable :data="parsedConfigData.products" />
          </a-tab-pane>
          <a-tab-pane key="extra" tab="扩展配置" v-if="parsedConfigData.extra">
            <ConfigDataTable :data="parsedConfigData.extra" />
          </a-tab-pane>
          <a-tab-pane key="advanced" tab="高级配置" v-if="parsedConfigData.advanced">
            <ConfigDataTable :data="parsedConfigData.advanced" />
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>

    <div v-else class="no-config">
      <a-empty description="暂无配置数据" />
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, watch, computed, defineComponent, h } from 'vue'
import { message } from 'ant-design-vue'

// 简单的配置数据表格组件
const ConfigDataTable = defineComponent({
  props: ['data'],
  setup(props: any) {
    const columns = [
      { title: '键', dataIndex: 'keyName', key: 'keyName' },
      { title: '值', dataIndex: 'value', key: 'value' },
      { title: '类型', dataIndex: 'type', key: 'type' }
    ]

    const dataSource = computed(() => {
      if (!props.data || typeof props.data !== 'object') return []

      return Object.entries(props.data).map(([key, value], index) => ({
        key: index,
        keyName: key,
        value: typeof value === 'object' ? JSON.stringify(value) : String(value),
        type: typeof value
      }))
    })

    return { columns, dataSource }
  },
  render() {
    return h('a-table', {
      columns: this.columns,
      dataSource: this.dataSource,
      pagination: false,
      size: 'small',
      bordered: true
    })
  }
})

// Props
interface Props {
  config?: any | null
  visible?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  config: null,
  visible: false
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  close: []
}>()

// 内部状态
const visible = ref(props.visible)

// 监听外部 visible 变化
watch(() => props.visible, (newVisible) => {
  visible.value = newVisible
})

// 监听内部 visible 变化，同步到外部
watch(visible, (newVisible) => {
  emit('update:visible', newVisible)
})

// 关闭处理
const handleClose = () => {
  visible.value = false
  emit('close')
}

// 解析配置数据
const parsedConfigData = computed(() => {
  if (!props.config?.configData) return null

  try {
    const data = typeof props.config.configData === 'string'
      ? JSON.parse(props.config.configData)
      : props.config.configData
    return data
  } catch (error) {
    return null
  }
})

// 格式化配置数据用于显示
const formatConfigData = (data: any) => {
  try {
    const parsed = typeof data === 'string' ? JSON.parse(data) : data
    return JSON.stringify(parsed, null, 2)
  } catch (error) {
    return typeof data === 'string' ? data : JSON.stringify(data, null, 2)
  }
}

// 获取配置类型名称和颜色
const getConfigTypeName = (type: number) => {
  const names = {
    1: 'PROVIDER_CHANNEL服务商渠道',
    2: 'APP_MERCHANT_CHANNEL应用商户渠道',
    3: 'APP_PRODUCT_CHANNEL应用产品渠道'
  }
  return names[type as keyof typeof names] || `类型${type}`
}

const getConfigTypeColor = (type: number) => {
  const colors = {
    1: 'blue',
    2: 'green',
    3: 'purple'
  }
  return colors[type as keyof typeof colors] || 'default'
}

// 导出配置信息
const exportConfig = () => {
  if (!props.config) return

  try {
    const exportData = {
      configId: props.config.configId,
      configType: props.config.configType,
      channelCode: props.config.channelCode,
      configData: props.config.configData,
      exportTime: new Date().toISOString()
    }

    const jsonString = JSON.stringify(exportData, null, 2)

    // 创建下载链接
    const blob = new Blob([jsonString], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `config-${props.config.configId}-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    message.success('配置信息导出成功')
  } catch (error) {
    message.error('导出失败：' + (error as Error).message)
  }
}

// 暴露方法供外部调用
defineExpose({
  open: () => {
    visible.value = true
  },
  close: () => {
    visible.value = false
  }
})
</script>

<style scoped>
.config-detail {
  padding: 0;
}

.mb-4 {
  margin-bottom: 16px;
}

.config-data-container {
  max-height: 400px;
  overflow: auto;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
}

.config-json {
  margin: 0;
  padding: 16px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #262626;
  background: transparent;
  white-space: pre-wrap;
  word-break: break-all;
}

.no-config {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

:deep(.ant-drawer-body) {
  padding: 16px;
}

:deep(.ant-drawer-header) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-card-head) {
  padding: 0 16px;
  min-height: 40px;
}

:deep(.ant-card-head-title) {
  font-size: 14px;
  font-weight: 500;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background-color: #fafafa;
}

:deep(.ant-tabs-content-holder) {
  padding-top: 16px;
}
</style>